package com.leetcode.Offer;

public class JZ12_2 {
    public boolean exist(char[][] board, String word) {
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[0].length; j++) {
                if (board[i][j] == word.charAt(0) && dfs(board, word.toCharArray(), i, j, 0, new boolean[board.length][board[0].length])) {
                    return true;
                }
            }
        }
        return false;
    }

    private boolean dfs(char[][] board, char[] word, int i, int j, int index, boolean[][] flag) {
        if (index == word.length) {
            return true;
        }
        if (i < 0 || j < 0 || i >= board.length || j >= board[0].length || flag[i][j] || board[i][j] != word[index]) {
            return false;
        }
        flag[i][j] = true;

        boolean res = dfs(board, word, i - 1, j, index + 1, flag) ||   //上
                dfs(board, word, i + 1, j, index + 1, flag) ||  //下
                dfs(board, word, i, j - 1, index + 1, flag) ||  //左
                dfs(board, word, i, j + 1, index + 1, flag);

        if (!res) {
            flag[i][j] = false;
        }
        return res;
    }

    public static void main(String[] args) {
        JZ12_2 jz12_2 = new JZ12_2();
        char[][] board = {
                {'A', 'B', 'C', 'E'},
                {'S', 'F', 'E', 'S'},
                {'A', 'D', 'E', 'E'}
        };
        System.out.println(jz12_2.exist(board, "ABCESEEEFS"));
    }

}
